package com.zlzsy.app.base.ui

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Environment
import android.support.design.widget.AppBarLayout
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.Toolbar
import android.util.Log
import android.webkit.*
import com.zlzsy.app.base.R
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.support.v4.swipeRefreshLayout
import org.jetbrains.anko.webView
import org.jetbrains.anko.wrapContent

/**
 * Created by niantuo on 2017/11/9.
 * 加载h5 界面的
 */
class H5Activity : BaseActivity() {

    companion object {
        val EXTRA_DATA_URL = "EXTRA_DATA_URL"
        private val TAG: String = H5Activity::class.java.simpleName

        fun startH5Activity(context: Context, url: String) {
            val intent = Intent(context, H5Activity::class.java)
            intent.putExtra(EXTRA_DATA_URL, url)
            context.startActivity(intent)
        }

    }

    private lateinit var mToolbar: Toolbar
    private lateinit var mWebView: WebView
    private lateinit var mRefreshLayout: SwipeRefreshLayout

    override fun initView() {
        coordinatorLayout {
            fitsSystemWindows = true
            appBarLayout {
                setTheme(R.style.Toolbar_Style)
                backgroundResource = R.color.colorPrimary
                mToolbar = toolbar {
                    setSupportActionBar(this)
                    setTitleTextColor(resources.getColor(android.R.color.white))
                }.lparams(matchParent, wrapContent) {
                    scrollFlags = AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL or
                            AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
                }
            }.lparams(matchParent, wrapContent)
            mRefreshLayout = swipeRefreshLayout {
                mWebView = webView {
                    settings.javaScriptEnabled = true
                    settings.defaultTextEncodingName = "utf-8"
                    settings.allowFileAccess = true
                    settings.loadWithOverviewMode = true
                    settings.setRenderPriority(WebSettings.RenderPriority.HIGH)
                    settings.cacheMode = WebSettings.LOAD_DEFAULT  //设置 缓存模式
                    // 开启 DOM storage API 功能
                    settings.domStorageEnabled = true
                    settings.javaScriptCanOpenWindowsAutomatically = true
                    settings.useWideViewPort = true//关键点
                    settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
                    webChromeClient = H5WebChromeClient()
                    webViewClient = H5WebViewClient()

                    //开启 database storage API 功能
                    settings.databaseEnabled = true
                    val cacheDirPath = Environment.getExternalStorageDirectory().absolutePath
                    //设置数据库缓存路径
                    settings.databasePath = cacheDirPath
                    //设置  Application Caches 缓存目录
                    settings.setAppCachePath(cacheDirPath)
                    //开启 Application Caches 功能
                    settings.setAppCacheEnabled(true)
                }
                setOnRefreshListener {
                    mWebView.reload()
                }
            }.lparams(matchParent, matchParent) {
                behavior = AppBarLayout.ScrollingViewBehavior()
            }
        }
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    private lateinit var mUrl: String

    override fun initData(savedInstanceState: Bundle?) {
        mUrl = intent.getStringExtra(EXTRA_DATA_URL)
        mWebView.loadUrl(mUrl)
        mRefreshLayout.isRefreshing = true

        Log.d(TAG, "url: $mUrl")
    }


    inner class H5WebChromeClient : WebChromeClient() {
        override fun onReceivedTitle(view: WebView?, title: String?) {
            setTitle(title)
        }
    }

    inner class H5WebViewClient : WebViewClient() {

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            Log.d(TAG, "url : ${request?.url}")
            return false
        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            Log.d(TAG, "onPageStarted: $url")
        }

        override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
            super.onReceivedError(view, request, error)
            Log.d(TAG, "onReceivedError : $error")
            mRefreshLayout.isRefreshing = false
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            Log.d(TAG, "url: $url")
            mRefreshLayout.isRefreshing = false
        }

    }

}